package com.tiancheng.trade.order.util.lock;

import com.tiancheng.trade.commom.core.utils.ServiceLocator;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * 锁
 *
 * @author kellen
 * @date 2024/4/23
 */
public final class Lock implements AutoCloseable {

    private RLock lock;
    private boolean lockRes;
    // 创建支付订单
    public static final String LOCK_ORDER_CREATE_PAY = "LOCK_ORDER_CREATE_PAY";
    // 支付
    public static final String LOCK_ORDER_PAY = "LOCK_ORDER_PAY";
    // 支付结果通知
    public static final String LOCK_NOTIFY_PAY = "LOCK_NOTIFY_PAY";
    // 退款
    public static final String LOCK_ORDER_REFUND = "LOCK_ORDER_REFUND";
    // 退款
    public static final String LOCK_ORDER_REFUND_SUBMIT = "LOCK_ORDER_REFUND_SUBMIT";
    // 订单状态上报
    public static final String LOCK_ORDER_STATUS_CHANGE = "LOCK_ORDER_STATUS_CHANGE";
    // 银行卡绑定
    public static final String LOCK_BANK_CARD_BINDING = "LOCK_BANK_CARD_BINDING";
    // 申请二维码
    public static final String LOCK_QR_ORDER = "LOCK_QR_ORDER";

    public Lock(String region, String key, int waitTime, int leaseTime) throws Exception {
        this(region, key, waitTime, leaseTime, TimeUnit.SECONDS);
    }

    public Lock(String region, String key, int waitTime, int leaseTime, TimeUnit timeUnit) throws Exception {
        RedissonClient redissonClient = ServiceLocator.getBean(RedissonClient.class);
        StringBuilder name = new StringBuilder();
        name.append(region).append("_").append(key);
        lock = redissonClient.getLock(name.toString());
        lockRes = lock.tryLock(waitTime, leaseTime, timeUnit);
    }

    public boolean getLockRes() {
        return lockRes;
    }

    @Override
    public void close() throws Exception {
        if(lock != null) {
            lock.forceUnlock();
        }
    }
}
